#!/usr/bin/env python

import json
import os
import sys

import jinja2


def show_help():
    print("Usage:")
    print("    jsontmpl [-f <INPUT-fILE>] [-O <OUTPUT-FILE>] <TEMPLATE-FILE>")
    return 0


def render(infile, outfile, tmplfile):
    text = infile.read()
    template = jinja2.Template(text)
    outfile.write(template.render(ARGS=json.load(tmplfile)))
    return 0


#   -f <INPUT-FILE>
#   -o <OUTPUT-FILE>
#   <TEMPLATE-FILE>
def main(argv: [str]) -> int:
    if len(argv) < 2:
        print("Missing parameters, type -h for help", file=sys.stderr)
        return 1

    if argv[1] == '-h' or argv[1] == '--help':
        return show_help()

    input_filepath = ""
    output_filepath = ""
    tmpl_filepath = ""

    i = 1
    while i < len(argv):
        if argv[i] == '-f':
            if (i + 1) >= len(argv):
                print("Uncompleted option '-f'", file=sys.stderr)
                return 1
            input_filepath = argv[i + 1]
            i += 2
            continue
        if argv[i] == '-o':
            if (i + 1) >= len(argv):
                print("Uncompleted option '-o'", file=sys.stderr)
                return 1
            output_filepath = argv[i + 1]
            i += 2
            continue

        if tmpl_filepath == "":
            tmpl_filepath = argv[i]
            i += 1
            continue

        #   不支持的参数
        print("Too many template file specified: {}".format(argv[i]), file=sys.stderr)
        return 1

    try:
        tmplfile = open(tmpl_filepath, 'r')

        outfile = sys.stdout
        if output_filepath != "":
            outfile = open(output_filepath, 'w+')

        infile = sys.stdin
        if input_filepath != "":
            infile = open(input_filepath, 'r')

        return render(infile, outfile, tmplfile)
    finally:
        if tmpl_filepath != "":
            tmplfile.close()
        if output_filepath != "":
            outfile.close()
        if input_filepath == "":
            infile.close()
        return 1


if __name__ == '__main__':
    sys.exit(main(sys.argv))
